<template>
    <el-table :data="departments" style="width: 100%" :tree-props="treeProps" border default-expand-all row-key="id">
        <el-table-column label="部门名称" prop="name"></el-table-column>
        <el-table-column label="上级部门" prop="parentName"></el-table-column>
        <el-table-column label="部门经理 ID" prop="ManagerId"></el-table-column>
        <el-table-column label="启用状态" prop="enable">
            <template #default="{ row }">
                <el-tag :type="row.enable ? 'success' : 'danger'">
                    {{ row.enable ? '启用' : '禁用' }}
                </el-tag>
            </template>
        </el-table-column>
        <el-table-column label="创建时间" prop="createTime"></el-table-column>
        <el-table-column label="修改时间" prop="updateTime"></el-table-column>
        <el-table-column label="操作">
            <template #default="{ row }">
                <el-button @click="editDepartment(row)" type="primary" size="small">编辑</el-button>
                <el-button @click="deleteDepartment(row.id)" type="danger" size="small">删除</el-button>
            </template>
        </el-table-column>
    </el-table>
</template>

<script setup>
import { ref, onMounted, inject } from 'vue';
const axios = inject('$axios'); // 从全局属性注入

// 部门数据
const departments = ref();

// 配置 tree-props，用来指示数据的树形结构
const treeProps = {
    children: 'children', // 子节点的字段
    label: 'name', // 节点名称的字段
    expandAll: true, // 默认展开所有节点
};

//获取部门信息
const GetDeparments = async () => {
    // 延迟 0.5 秒发送请求
    setTimeout(async () => {
        try {
            var result = await axios.get('/Department/QueryDepartmentResultsAsync');
            if (result.statusCode == 200 && result.success == true) {
                departments.value = result.response;
            }
        } catch (error) {
            console.error("请求失败", error);
        }
    }, 500); // 延迟500毫秒
}

//重新加载数据
const ReloadData = async () => {
    await GetDeparments();
}

const emit = defineEmits();
// 通知父组件编辑
const editDepartment = (department) => {
    // 使用 emit 发送事件到父组件，并传递数据
    emit('edit-department', department);
};

const deleteDepartment = async (id) => {
    const result = await axios.get(`/Department/DeletedDepartmentByIdAsync?id=${id}`);
    if (result.statusCode == 200 && result.success == true) {
        await GetDeparments();
        ElMessage.success(result.message);
    } else {
        ElMessage.error(result.message);
    }
}

onMounted(async () => {
    await GetDeparments();
})

defineExpose({
    ReloadData,
});

</script>

<style scoped></style>